package ru.spbu.math.seabattle.server.jms;

import java.io.PrintWriter;
import java.io.Serializable;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;

import ru.spbu.math.seabattle.client.jms.common.JmsQueueHelper;

public class JMSEchoServer extends AbstractJMSServer {

	public static final String ECHO_QUEUE_NAME = "ECHO-QUEUE";
	private static final String BROKER_ADDRESS = "tcp://0.0.0.0:9001";

	public JMSEchoServer(String brokerAddress) {
		super(brokerAddress, "ECHO-SERVER", ECHO_QUEUE_NAME);
		System.out.println("Server started");
	}

	
	static PrintWriter received;
	@Override
	public void onMessage(Message message) {
		
		if (message instanceof ObjectMessage) {

			try {

				if (message.getJMSReplyTo() != null) {

					Serializable object = ((ObjectMessage) message).getObject();
					JmsQueueHelper helper = new JmsQueueHelper();

					helper.start(brokerAddress, message.getJMSReplyTo());

					helper.send(object);
				}

			} catch (JMSException e) {
				// TODO: Use log4j
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) throws Exception {

		JMSEchoServer server;
		server = new JMSEchoServer(BROKER_ADDRESS);
		server.start();
	}
}
